import router from './router'
import store from './store'
import {
	Message
} from 'element-ui'
import {
	generateUUID,
	isFalse
} from './utils/util.js'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
	getToken,
	getDoorToken,
	getType,
	clearStorage
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
	showSpinner: true
}) // NProgress Configuration

const whiteList = ['/login', `/404`, '/no_token_portal', '/app/worker/view_workorder', '/app/view/workorder_detail',
	'/app/view/workorder_building', '/app/worker/view_building', '/app/view/app_view_building_device',
	'/app/view/app_view_building_device_choose', '/app/app_download',
	'/app/worker/photo_requirement', '/app/worker/photo_requirement_one', '/customer_check', '/supplier_check'
] // no redirect whitelist

const catchList = []

router.beforeEach(async (to, from, next) => {
	console.log('from', from)
	//debugger
	if (to.fullPath === '/') {
		next(`/login`)
		NProgress.done()
	} else {
		console.log('to:', to)
		if (to.fullPath === '/statistics/big_data') {
			let routeData = router.resolve({
				path: '/dashboard'
			})
			window.open(routeData.href, '_blank', 'noopener,noreferrer')
			next(false)
		} else {
			// start progress bar
			// 去除加载页的开启
			if (to.name !== 'personal_handler_contract_apply') {
				NProgress.start()

				// set page title
				document.title = getPageTitle(to.meta.title)
			}
			// determine whether the user has logged in
			const hasToken = getToken()

			// 已登入并且不选择登入页面
			if (hasToken && to.path.indexOf('login') === -1) {
				console.log('1------', store)
				const hasGetUserInfo = store.getters.name
				//路由权限
				let hasRoles
				hasRoles = store.getters.roles && store.getters.roles.length > 0

				if (catchList.includes(to.name)) {
					store.commit('keep/KEEP_ALIVE', to.name)
				}

				if (hasRoles) {
					if ((!to.query || !to.query.uuid) && !!to.name && !!to.params) {
						let uuid = generateUUID()
						store.commit('keep/PUT_PAGE_PARAMS', {
							uuid: uuid,
							data: to.params || {}
						})
						next({
							name: to.name,
							params: to.params,
							query: {
								uuid: uuid
							}
						})
					} else {
						next()
					}
				} else {
					try {
						// get user info
						// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
						let info
						if (!!hasToken) {
							info = await store.dispatch('user/getInfo')
						}
						const {
							rights,
							isUser
						} = info
						console.log('right------', rights)
						// generate accessible routes map based on roles
						const accessRoutes = await store.dispatch('permission/generateRoutes', rights)

						// const accessRoutes = await store.dispatch("permission/generateDynamicRoutes", {roles:roles,rights:rights});

						// dynamically add accessible routes
						console.log('accessRoutes------', accessRoutes)
						router.addRoutes(accessRoutes)

						if (!!isUser && ((rights || []).length <= 0)) {
							await store.dispatch('user/resetUser')
							Message.error('该用户无权限，或角色已被禁用，请联系管理员')
							next(`/login`)
						} else {
							if ((!to.query || !to.query.uuid) && !!to.name && !!to.params) {
								let uuid = generateUUID()
								store.commit('keep/PUT_PAGE_PARAMS', {
									uuid: uuid,
									data: to.params || {}
								})
								next({
									name: to.name,
									params: to.params,
									query: {
										uuid: uuid
									}
								})
							} else {
								next({
									...to,
									replace: true
								})
							}
						}
					} catch (error) {
						// remove token and go to login page to re-login
						await store.dispatch('user/resetToken')
						console.log(error)
						//Message.error(error.message || "Has Error");

						next(`/login`)
					}
				}
			} else {
				console.log('2------')
				// token失效 或者 进入登录页面
				/* has no token*/

				//路由在白名单内，登入界面
				if (whiteList.indexOf(to.path) !== -1) {
					// in the free login whitelist, go directly
					next()
				} else {
					// 不在白名单内，重定向到toekn失效页
					// await store.dispatch("user/resetUser");
					// next(`/no_token_portal`);
					NProgress.done()
				}
			}
		}
	}

})

// router.beforeResolve(async (to, from, next) => {
// 	if(!!to.query && !!to.query.uuid) to.meta.ownParams = store.getters.pageParamsMap.get(to.query.uuid) || {};
// 	console.log('to', to);
// 	console.log('from', from);
// 	//console.log('next', next);
// 	next();
// })

router.afterEach(() => {
	// finish progress bar
	NProgress.done()
})
